package game;

import game.screens.Screen;
import game.screens.StartScreen;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;

import asciiPanel.AsciiPanel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;

import javax.swing.JMenuBar;

public class ApplicationMain extends JFrame implements KeyListener,ActionListener {
	private static final long serialVersionUID = 1060623638149583738L;
	
	private AsciiPanel terminal;
	private Screen screen;
	public JMenuItem open,save; //decidere se public o private
	JFileChooser fc; 			//decidere se public o private
	/*Gestisce l'interfaccia grafica e l'input (Tastiera e file)*/
	public ApplicationMain(){
		super();
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		

        //Build the first menu.
		fc=new JFileChooser();
        JMenu menu = new JMenu("Partita");
        menuBar.add(menu);
		open = new JMenuItem("Open");
		save = new JMenuItem("Save");
		open.addActionListener(this);
		save.addActionListener(this);
		menu.add(open);
		menu.add(save);
		terminal = new AsciiPanel();
		getContentPane().add(terminal);
		pack();
		screen = new StartScreen();
		addKeyListener(this);
		
		
		
		repaint();
	}
	
	@Override
	public void repaint(){
		terminal.clear();
		screen.displayOutput(terminal);
		super.repaint();
	}

	@Override
	public void keyPressed(KeyEvent e) {
		screen = screen.respondToUserInput(e);
		repaint();
	}

	@Override
	public void keyReleased(KeyEvent e) { }

	@Override
	public void keyTyped(KeyEvent e) { }
	
	public static void main(String[] args) {
		ApplicationMain app = new ApplicationMain();
		app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		app.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		
		if(e.getSource()==open)
		{
			int returnVal=fc.showOpenDialog(ApplicationMain.this);
			if(returnVal==JFileChooser.APPROVE_OPTION)
			{
				File file=fc.getSelectedFile();
				screen=screen.load(file);
				
			}
		}
		if((e.getSource()==save))
		{
			int returnVal=fc.showSaveDialog(ApplicationMain.this);
			if(returnVal== JFileChooser.APPROVE_OPTION)
			{
				File file=fc.getSelectedFile();
				screen=screen.save(file);
			}
					
		}
		repaint();
	}
}
